#include <QUdpSocket>
#include <QThread>
#include "udpComunInPTh.h"
#include "macro.h"

UdpCommunInPeerThread::UdpCommunInPeerThread(quint8 paraID, QObject *parent):
    QObject(parent)
{
    ID=paraID;
    udpSocketPeerThread=new QUdpSocket();
    udpSocketPeerThread->bind(ServerPortData,QUdpSocket::ShareAddress|QUdpSocket::ReuseAddressHint);
    connect(udpSocketPeerThread,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));
    qDebug()<<"new udpSocket created in "<<thread();
}

void UdpCommunInPeerThread::slotSendData(QByteArray data,QString destAddr,
    quint16 destPort,quint8 paraID)
{
    if(paraID!=ID)
        return;
    //qDebug()<<"Send udp in thread "<<thread();
    if(!destAddr.isEmpty()&&destAddr.count(".")==3)
        udpSocketPeerThread->writeDatagram(data,QHostAddress(destAddr),destPort);
}

void UdpCommunInPeerThread::processPendingDatagrams()
{
    QByteArray d;
    udpSocketPeerThread->readDatagram(d.data(),0);
}
